#include "TcpConnection.hpp"

TcpConnection::~TcpConnection(){
    if (inputBuffer_) delete inputBuffer_;
    if (outputBuffer_) delete outputBuffer_;
    close(fd_);
}

int TcpConnection::readSocket() {
    std::unique_lock<std::mutex> ulock(inMtx_);
    int rlen = inputBuffer_->socketRead(fd_);
    ulock.unlock();
    if (rlen <= 0){
        return rlen;
    }
    // std::cout << charBuff << std::endl;
    return rlen;
}

int TcpConnection::writeSocket() {
    std::unique_lock<std::mutex> ulock(outMtx_);
    int res = outputBuffer_->sendData(fd_);
    ulock.unlock();
    if (res < 0) {
        perror("TcpConnection::writeSocket");
        return res;
    }
    return res;
}


// int TcpConnection::writeToBuffer(const std::vector<char>& buff) {
//     return outputBuffer_->appendString(buff.data(), buff.size());
// }


// HttpRequest* TcpConnection::decodeReqFromBuff() {
//     httpRequest_->reset();
//     while (httpRequest_->getState() == ParseState::ParseLine) {
//         httpRequest_->parseLine(readSplitFromBuffer("\r\n", 2));
//     }
//     if (httpRequest_->getState() == ParseState::ParseErr) {
//         return nullptr;
//     }
//     while (httpRequest_->getState() == ParseState::ParseHeaders) {
//         httpRequest_->parseHeader(readSplitFromBuffer("\r\n", 2));
//     }
//     if (httpRequest_->getState() == ParseState::ParseErr) {
//         return nullptr;
//     }
//     httpRequest_->parseBody(inputBuffer_);
//     if (httpRequest_->getState() == ParseState::ParseErr) {
//         return nullptr;
//     }
//     return httpRequest_;
// }

void TcpConnection::closeConnection(){
    loop_->delEvent(fd_);
}